package com.lmy.mySpringboot;

import com.lmy.mySpringboot.config.LmyConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * 初始化器
 * 1.创建Spring容器
 * 2.加载/关联Spring容器的配置-按照注解的方式
 * 3.完成Spring容器配置的bean的创建和依赖注入
 * 4.创建前端控制器 DispatcherServlet 并让其持有Spring容器
 * 5.当DispatcherServlet持有容器，就可以进行请求分发
 * 6.onStartup 是tomcat来调用，并把ServletContext对象传入
 */
public class LmyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        System.out.println("startup....");
        //加载Spring web application configuration
        AnnotationConfigWebApplicationContext ac
                = new AnnotationConfigWebApplicationContext();
        //在容器中注册配置类LmyConfig.class
        ac.register(LmyConfig.class);
        //完成bean的创建和配置
        ac.refresh();
        //创建/注册前端控制器，并让器持有spring容器，来进行映射分发
        DispatcherServlet dispatcherServlet
                = new DispatcherServlet(ac);
        //将dispatcherServlet加入到servletContext上下文中
        //返回了 ServletRegistration.Dynamic 对象
        ServletRegistration.Dynamic registration
                = servletContext.addServlet("app", dispatcherServlet);
        //当tomcat启动时，加载 dispatcherServlet
        registration.setLoadOnStartup(1);
        //拦截请求并进行分发处理
        registration.addMapping("/");
    }
}
